package org.hefan.user.controller;

import org.hefan.basic.exception.BusinessException;
import org.hefan.basic.util.AjaxResult;
import org.hefan.user.service.IUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.Map;

/**
 * 发送验证码controller
 */
@RestController
@RequestMapping("/verifycode")
public class VerifycodeController {

    /**
     * 注入用户userService
     */
    @Autowired
    private IUserService userService;

    /**
     * post请求
     * 登陆发送手机验证码
     * @param map {phone=15047877872}
     * @return AjaxResult
     */
    @PostMapping("/smsCode")
    public AjaxResult getSmsCode(@RequestBody Map<String, String> map) {
        // map {phone=15047877872}
        try {
            String phone = map.get("phone");
            userService.sendSms(phone);
            return new AjaxResult();
        } catch (BusinessException e) {
            e.printStackTrace();
            return AjaxResult.me().setSuccess(false).setMsg("发送失败," + e.getMessage());
        } catch (Exception e) {
            e.printStackTrace();
            return AjaxResult.me().setSuccess(false).setMsg("系统异常," + e.getMessage());
        }
    }

    /**
     * post请求
     * 绑定发送手机验证码
     * @param map {phone=15047877872}
     * @return AjaxResult
     */
    @PostMapping("/binderCode")
    public AjaxResult getBinderCode(@RequestBody Map<String, String> map) {
        try {
            String phone = map.get("phone");
            userService.sendBinderCode(phone);
            return new AjaxResult();
        } catch (BusinessException e) {
            e.printStackTrace();
            return AjaxResult.me().setSuccess(false).setMsg("发送失败," + e.getMessage());
        } catch (Exception e) {
            e.printStackTrace();
            return AjaxResult.me().setSuccess(false).setMsg("系统异常," + e.getMessage());
        }
    }

    /**
     * post请求
     * 手机验证码登陆发送验证码
     * @param  {"phone":this.phoneForm.phone}
     * @return AjaxResult
     */
    @PostMapping("/smsCodeByPhone")
    public AjaxResult smsCodeByPhone(@RequestBody Map<String, String> map) {
        try {
            System.out.println(map);
            String phone = map.get("phone");
            userService.smsCodeByPhone(phone);
            return new AjaxResult();
        } catch (BusinessException e) {
            e.printStackTrace();
            return AjaxResult.me().setSuccess(false).setMsg("发送失败," + e.getMessage());
        } catch (Exception e) {
            e.printStackTrace();
            return AjaxResult.me().setSuccess(false).setMsg("系统异常," + e.getMessage());
        }
    }
}
